package com.jweb.framework.security.crypto.cipher.asymmetric;

import java.security.Key;

import javax.crypto.Cipher;

import com.jweb.framework.security.crypto.common.EAlgorithm;
import com.jweb.framework.security.crypto.common.ECipherMode;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：非对称加解密默认处理
 */
public class DefaultAsymCipherer implements AsymCipherer {
	
	protected EAlgorithm algorithm = EAlgorithm.RSA;
	protected ECipherMode mode ;
	protected Key key ;

	public void setAlgorithm(EAlgorithm algorithm) {
		this.algorithm = algorithm;
	}

	public void setMode(ECipherMode mode) {
		this.mode = mode;
	}
	
	public void setKey(Key key) {
		this.key = key;
	}

	@Override
	public byte[] encrypt(byte[] bytes) {
		
		try {
			Cipher cipher = Cipher.getInstance(this.algorithm.toString());
			int num = mode.ordinal() ;
			switch (num) {
				case 0: // 加密
					/**
					 * init(int opmode , --此 Cipher
					 * 的操作模式（为以下之一：ENCRYPT_MODE、DECRYPT_MODE、WRAP_MODE 或
					 * UNWRAP_MODE） Key key , --加密密钥 AlgorithmParameters params)
					 * --算法参数 用密钥和一组算法参数初始化此Cipher.
					 */
					cipher.init(Cipher.ENCRYPT_MODE, this.key);
					break;
				case 1: // 解密
					cipher.init(Cipher.DECRYPT_MODE, this.key);
					break;
				default:
					throw new AsymmetricEncryptionException("error encrypting/decrypting message: invalid mode;mode = "+ this.mode);
			}
			
			return cipher.doFinal(bytes);
		} catch (Exception e) {
			throw new AsymmetricEncryptionException("error encrypting/decrypting message; mode=" + this.mode, e);
		}
	}
	
	
	
}
